package com.miniapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miniapp.entity.Role;
import com.miniapp.entity.UserRole;
import com.miniapp.mapper.RoleMapper;
import com.miniapp.mapper.UserRoleMapper;
import com.miniapp.service.RoleService;
import com.miniapp.domain.vo.RoleQueryVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色Service实现类
 *
 * @author yourname
 * @date 2025-09-08
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public List<String> getUserRoleCodes(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }
        return baseMapper.selectRoleCodesByUserId(userId);
    }

    @Override
    public List<Long> getUserRoleIds(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }
        return baseMapper.selectRoleIdsByUserId(userId);
    }

    @Override
    public IPage<Role> queryRolePage(RoleQueryVO queryVO) {
        Page<Role> page = new Page<>(queryVO.getPageNum(), queryVO.getPageSize());
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();

        // 角色名称模糊查询
        if (queryVO.getRoleName() != null) {
            queryWrapper.like(Role::getRoleName, queryVO.getRoleName());
        }
        // 角色编码模糊查询
        if (queryVO.getRoleCode() != null) {
            queryWrapper.like(Role::getRoleCode, queryVO.getRoleCode());
        }
        // 状态筛选
        if (queryVO.getStatus() != null) {
            queryWrapper.eq(Role::getStatus, queryVO.getStatus());
        }

        queryWrapper.orderByDesc(Role::getCreateTime);

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean saveRole(Role role) {
        // 检查角色编码是否已存在
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getRoleCode, role.getRoleCode());
        long count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("角色编码已存在");
        }
        return save(role);
    }

    @Override
    public boolean updateRole(Role role) {
        // 检查角色编码是否已被其他角色使用
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getRoleCode, role.getRoleCode())
                .ne(Role::getId, role.getId());
        long count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("角色编码已存在");
        }
        return updateById(role);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean assignUserRoles(Long userId, List<Long> roleIds) {
        // 先删除用户原有角色
        userRoleMapper.deleteByUserId(userId);

        // 如果角色ID列表为空，直接返回
        if (CollectionUtils.isEmpty(roleIds)) {
            return true;
        }

        // 批量插入新的角色关联
        List<UserRole> userRoleList = new ArrayList<>();
        for (Long roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleList.add(userRole);
        }

        return userRoleMapper.batchInsert(userRoleList) > 0;
    }
}
